package top.kangshuai.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.kangshuai.dao.TbTokenInfoDAO;
import top.kangshuai.dao.TbUserDAO;
import top.kangshuai.entity.TbTokenInfo;
import top.kangshuai.entity.TbUser;
import top.kangshuai.exception.AppException;
import top.kangshuai.model.UserModel;
import top.kangshuai.service.UserService;
import top.kangshuai.utils.JsonMessage;
import top.kangshuai.utils.MyUtils;
/**
 *  
 * @author ks187
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

  @Autowired
  private TbUserDAO tbUserDAO;
  
  @Autowired
 private TbTokenInfoDAO tbTokenInfoDAO;
  @Override
  public JsonMessage login(UserModel model) throws Exception {
    // 非数据库问题直接 返回JsonMessage
    TbUser user = model.getUser();
    // 校验用户输入
    if (MyUtils.isEmpty(user.getUsername())) {
      return JsonMessage.getFail("用户名必须填写！");
    }
    if (MyUtils.isEmpty(user.getPassword())) {
      return JsonMessage.getFail("密码必须填写！");
    }
    // 数据库校验，只要不出现更新数据的语句不需要抛出异常
    TbUser user2 = tbUserDAO.queryByName(user);
    if (user2 == null) {
      return JsonMessage.getFail("用户名不存在！");
    }
    if (!user2.getPassword().equalsIgnoreCase(user.getPassword())) {
      return JsonMessage.getFail("用户密码错误！");
    }
    // 需要将登录信息保存到Token表
    TbTokenInfo tokenInfo=model.getTbTokenInfo();
    tokenInfo.setInfo(user2.getUid()+"");
    //查询数据库中是否存在用户信息
    int result=0;
    TbTokenInfo sInfo=tbTokenInfoDAO.queryUser(tokenInfo);
    if (sInfo==null) {
      //不存在就添加
    result=  tbTokenInfoDAO.addUser(tokenInfo);
    }else {
      //存在就更新
      sInfo.setInfo(tokenInfo.getInfo());
      result=tbTokenInfoDAO.updateUser(sInfo);
      
    }
    // 如果数据库更新的结果不是预期效果需要通过抛出异常打断流程，回滚事务
    if (result != 1) {
      throw AppException.getAppException(500, "登录状态异常");
    }
    return JsonMessage.getSuccess("登录成功！");
  }

  @Override
  public JsonMessage logout(UserModel model) throws Exception {
    tbTokenInfoDAO.deleteUser(model.getTbTokenInfo());
    
    return JsonMessage.getSuccess("退出成功！");
  }
  
  @Override
  public JsonMessage getUserInfo(UserModel model)throws Exception{
    TbUser user=tbUserDAO.queryByToken(model.makeTokenInfo());
    //不要返回敏感信息给客户端
    if (user!=null) {
      user.setUid(null);
      user.setPassword(null);
      user.setIsEnable(null);
    }
    
    JsonMessage message=JsonMessage.getSuccess("");
    message.getDatas().put("user", user);
    return message;
  }
  
}
